package com.etone.autotesting.socketservice.impl;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.etone.autotesting.manager.impl.ConditionSearchManager;

public class NettyServerHandler extends SimpleChannelUpstreamHandler {
	/**
 * 
 */
	public ConditionSearchManager searchManager;

	private StringBuilder builder;

	public NettyServerHandler() {
		searchManager = new ConditionSearchManager();
		builder = new StringBuilder();
	}

	/**
 * 			
 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		ChannelBuffer stream = (ChannelBuffer) e.getMessage();
		String functionJson = new String(stream.array(), "UTF-8");
		builder.append(functionJson);
		if (functionJson.endsWith("XOOX")) {
			Integer buLength = builder.length();
			builder = builder.delete(buLength-4, buLength);
			//System.out.println(builder.toString());
			searchManager.addFunctionCondition(builder.toString());
			builder = new StringBuilder();
		}

	}

	/**
 * 
 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		e.getChannel().close();
	}
}